// cloudfunctions/submitWithdraw/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { userId, amount, cardId } = event
    
    if (!userId || !amount || amount < 100) {
      return { success: false, message: '提现参数错误' }
    }
    
    // 开启事务
    const transaction = await db.startTransaction()
    
    try {
      // 1. 获取用户积分
      const pointsRes = await transaction.collection('user_points')
        .where({ userId: userId })
        .get()
      
      if (!pointsRes.data || pointsRes.data.length === 0) {
        await transaction.rollback()
        return { success: false, message: '用户积分记录不存在' }
      }
      
      const pointsData = pointsRes.data[0]
      
      // 2. 检查积分是否足够
      if (pointsData.points < amount) {
        await transaction.rollback()
        return { success: false, message: '积分不足，无法提现' }
      }
      
      // 3. 获取用户默认银行卡（如果未指定cardId）
      let bankCard;
      if (cardId) {
        const cardRes = await transaction.collection('user_bank_cards')
          .doc(cardId)
          .get()
        bankCard = cardRes.data;
      } else {
        const cardRes = await transaction.collection('user_bank_cards')
          .where({
            userId: userId,
            isDefault: true
          })
          .get()
        if (!cardRes.data || cardRes.data.length === 0) {
          await transaction.rollback()
          return { success: false, message: '未找到默认银行卡' }
        }
        bankCard = cardRes.data[0];
      }
      
      // 4. 生成提现记录
      const withdrawRecord = {
        recordId: `WDR_${Date.now()}`,
        type: 2,                // 2=提现
        amount: amount,
        bankCard: bankCard.cardNumberDisplay,  // 显示后四位
        bankName: bankCard.bankName,
        createTime: db.serverDate(),
        status: 1,              // 1=处理中
        remark: `积分提现到${bankCard.bankName}`
      }
      
      // 5. 更新用户积分
      await transaction.collection('user_points').doc(pointsData._id).update({
        data: {
          points: _.inc(-amount),
          records: _.unshift(withdrawRecord)
        }
      })
      
      // 6. 提交事务
      await transaction.commit()
      
      return { success: true, message: '提现申请已提交' }
      
    } catch (error) {
      await transaction.rollback()
      throw error
    }
    
  } catch (error) {
    console.error('提现失败:', error)
    return { success: false, message: '提现失败' }
  }
}